import {
    Location,
    Admin,
    Building,
    Company,
    Floor,
    Project,
    SearchRet
} from '../../../shared/model/defination';
import { Component, OnInit } from '@angular/core';
import { Helper } from '../../common/index';
import { ControlBase } from '../../../shared/dynamicform/controlbase';
import { TextBox } from '../../../shared/dynamicform/textbox-control';
import { SelectBox } from '../../../shared/dynamicform/selectbox-control';
import {
    EmailValidator,
    MobileValidator
} from '../../../shared/dynamicform/my-validator';
import { FormGroup, Validators } from '@angular/forms';
import { Observable } from 'rxjs/Rx';
import { Router, ActivatedRoute, Params, Route } from '@angular/router';
import { FloorService } from '../../../services/floor-service';
import { CompanyRequest, CompanyLocation } from '../../../dtos/CompanyRequest';
import { MdlSnackbarService } from '@angular-mdl/core';
import { CompanyService } from '../../../services/company-service';
import { ProjectService } from '../../../services/project-service';
import { BuildingService } from '../../../services/building-service';
import { UserService } from '../../../services/user-service';
import { SessionService, SessionUser } from '../../../services/session-service';
import { DOMAIN } from '../../../app.config';
import * as _ from 'lodash';
import { CustomError } from '../../../services/auth-inteceptor';

@Component({
    selector: 'company-edit',
    templateUrl: './edit.component.html',
    styleUrls: ['./edit.component.scss'],
    providers: [
        FloorService,
        CompanyService,
        ProjectService,
        BuildingService,
        UserService,
        SessionService
    ]
})
export class EditComponent implements OnInit {
    public isPosting = false;
    public get Location() {
        if (
            !this.company ||
            !this.company[0] ||
            !this.company[0].locations ||
            this.company[0].locations.length === 0
        ) {
            return {
                building: '',
                floor: '',
                unit: ''
            };
        }
        const location: Location = this.company[0].locations[0];
        return {
            building:
                location.building.buildingAlias ||
                location.building.buildingNumber,
            floor: location.floor.index,
            unit: location.unit.name
        };
    }

    public get IsEdit() {
        return this._route.snapshot.params['id'] !== undefined;
    }
    public get CanEditProject() {
        return this.userRole === '管理员';
    }
    public get CanEditCompany() {
        return this.userRole.toLowerCase() !== 'hr';
    }

    public IsUserProperty = this._sessionService.isUserProperty;
    public IsUserHr = this._sessionService.isUserHr;
    public showTable = false;
    private _editItem: Admin;
    public isFormPosting = false;
    public locationConfigs: any;
    public projectConfigs: Array<any>;
    public floorConfigs: any;
    public companyConfig: any;
    public selectedCompany: number;
    public locationProperties: Array<Location> = [];
    public company: Array<Company>;

    public selectedGender: number;
    public uploadPercent = 0;
    formInputs: ControlBase<any>[];
    formControls: any;
    public selectedRole: number;
    public staff: any = {};
    public avatarPhoto: any[] = [];
    public faceIds: number[] = [];
    public identifyPhoto: any[] = [];
    public userRole = '';
    // public uploadedPhotoIds: number[] = [];

    constructor(
        private _floorService: FloorService,
        private _route: ActivatedRoute,
        private _router: Router,
        private _companyService: CompanyService,
        private _mdlSnackbarService: MdlSnackbarService,
        private _projectService: ProjectService,
        private _buildingService: BuildingService,
        private _userService: UserService,
        private _sessionService: SessionService
    ) {}

    async ngOnInit() {
        try {
            // let session: Admin = await this._sessionService.getCurrentUser();
            // this.userRole = session.roles[0].roleName;
            this.isPosting = true;
            const userId = this.IsEdit ? +this._route.snapshot.params['id'] : 0;
            if (userId) {
                this.showTable = true;
                this._editItem = await this._userService
                    .Get(userId)
                    .toPromise();
                // let editUserRoleName = this._editItem.roles[0].roleName;
                this.selectedGender = this._editItem.gender;
                this.locationProperties = this._editItem.company.locations;
                this.company = [this._editItem.company];
                const identityPhotos = (this._editItem as any).userPhotos;
                identityPhotos &&
                    identityPhotos.length &&
                    identityPhotos.forEach((p: any) => {
                        this.identifyPhoto.push({
                            id: p.photo.id,
                            path: p.photo.path,
                            faceId: p.photo.facePhotoId
                        });
                    });
                const companyId = this._editItem.company.id;
                const company = await this._companyService
                    .Get(companyId)
                    .toPromise();
            } else if (this._sessionService.isUserHr) {
                this.company = [this._sessionService.Managable];
            }
            if (this._sessionService.isUserProperty) {
                const projectId = this._sessionService.Managable.id;
                const resp = await this._companyService
                    .getAllCompanyOfProject(projectId)
                    .toPromise();
                this.companyConfig = resp.items;
                // this.company = this._sessionService.Managable
            }
            this.formControls = this._setForm(this._editItem);
        } catch (e) {
            console.log(e);
            if (e.status === 401) {
                this._router.navigate(['/login']);
            }
        } finally {
            this.isPosting = false;
        }
    }

    private _setForm(data: any): any {
        this.formInputs = [
            new TextBox({
                type: 'text',
                key: 'mobile',
                label: '手机号',
                value: data ? data.mobile : '',
                required: true,
                // disabled: this.IsEdit,
                order: 2,
                groupId: 4,
                require: true,
                validators: [Validators.required, MobileValidator()]
            }),
            new TextBox({
                type: 'text',
                key: 'email',
                label: 'Email',
                value: data ? data.email : '',
                required: true,
                order: 1,
                groupId: 2,
                require: true,
                validators: [EmailValidator()]
            }),
            new TextBox({
                type: 'text',
                key: 'userName',
                label: '姓名',
                value: data ? data.userName : '',
                required: true,
                order: 1,
                groupId: 1,
                require: true,
                validators: Validators.required
            }),
            new SelectBox({
                key: 'gender',
                label: '性别',
                options: [{ key: '女', value: 0 }, { key: '男', value: 1 }],
                value: 0,
                order: 2,
                groupId: 3,
                require: true,
                // disabled: !this.CanEditCompany,
                validators: Validators.required
            })
        ];
        if (this.IsUserProperty) {
            this.formInputs.push(
                new SelectBox({
                    key: 'company',
                    label: '公司名称',
                    options:
                        this.companyConfig &&
                        <Array<any>>this.companyConfig.map(c => {
                            return {
                                key: c.name,
                                value: c.id
                            };
                        }),
                    value: data ? data.company.id : -1,
                    order: 2,
                    groupId: 0,
                    require: true,
                    // disabled: !this.CanEditCompany,
                    validators: Validators.required
                })
            );
        }
        return Helper.setGroupForm(this.formInputs);
    }
    async save(df: any) {
        this.isFormPosting = true;
        const form = <FormGroup>df.form;
        if (!form.valid) {
            return false;
        }
        const request: any = {
            userName: form.value.userName,
            gender: form.value.gender,
            mobile: form.value.mobile,
            email: form.value.email,
            companyId: this.company[0].id,
            avatar: '',
            photoIds: this.identifyPhoto.map(ip => ip.id)
        };
        let action;
        if (!this.IsEdit) {
            action = this._userService.Create(request).toPromise();
        } else {
            request.id = this._editItem.id;
            action = this._userService.Update(request).toPromise();
        }
        try {
            this.isPosting = true;
            const resp = await action;
            if (resp) {
                this._mdlSnackbarService.showToast('保存成功！', 2000);
                this._router.navigate(['/user']);
            }
        } catch (e) {
            if (e instanceof CustomError) {
                const msg = Object.keys(e.msg)
                    .map(k => e.msg[k][0])
                    .join(',');

                this._mdlSnackbarService.showToast(msg, 2000);
            } else {
                this._mdlSnackbarService.showToast(e.msg, 2000);
            }
        } finally {
            this.isFormPosting = false;
            this.isPosting = false;
        }
    }
    public onPhotoUploadError(event) {
        this._mdlSnackbarService.showToast(event.msg, 2000);
    }

    private _getCanEditRoles() {
        // let sessionRole = this.userRole.toLowerCase();
        // let sessionRoleMap = this.roleMap.find(r => r.key.toLowerCase() === sessionRole);
        // return this.roleMap.filter(r => r.value > sessionRoleMap.value);
    }

    public async onLoadFormData(form) {
        console.log(form);
        this.staff.userName = form.userName;
        this.staff.email = form.email;
        this.staff.phone = form.mobile;
        if (this.companyConfig) {
            const companyId = form.company;
            const company = (this.companyConfig as Array<any>).find(
                c => c.id === companyId
            );
            if (company) {
                this.company = [company];
            }
            console.log(company);
        }
    }
}
